/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package digitaldreamers.libraries.games.servers.networkmanagement.concrete;

import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.AbPacketHandler;
import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.IConnectionHandler;
import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.IGameServer;
import java.net.Socket;
import java.util.ArrayList;

/**
 *
 * @author DaoLe
 */
public class ConnectionHandlerFactory {
    /**
     * The capacity of the connection handler pool.
     */
    private static final int CAPACITY = 500;
    
    /**
     * Connection handler pool.
     */
    private static ArrayList<IConnectionHandler> connectionHandlerPool = new ArrayList<>(CAPACITY);
    
    /**
     * Create a new connection handler. This function support pooling.
     * @param pSocket The pSocket.
     * @param pGameServer The game server.
     * @param pPacketHandler The packet handler for this connection handler.
     * @param pConnectionCheckEnable Enable connection status checking or not.
     * @return The connection handler.
     */
    public static IConnectionHandler createNewConnectionHandler(Socket pSocket, IGameServer pGameServer, AbPacketHandler pPacketHandler, boolean pConnectionCheckEnable) {
        if(connectionHandlerPool.size() > 0) {
            ConnectionHandler connectionHandler = (ConnectionHandler)connectionHandlerPool.remove(connectionHandlerPool.size() - 1);
            connectionHandler.setInitialState(pSocket, pGameServer, pPacketHandler, pConnectionCheckEnable);
            return connectionHandler;
        }
        return new ConnectionHandler(pSocket, pGameServer, pPacketHandler, pConnectionCheckEnable);
    }
    
    /**
     * Release a connection handler to the pool.
     * @param pConnectionHandler The connection handler to release.
     */
    static void releaseConnectionHandler(IConnectionHandler pConnectionHandler) {
        if(connectionHandlerPool.size() < CAPACITY) {
            if(!connectionHandlerPool.contains(pConnectionHandler)) {
                connectionHandlerPool.add(pConnectionHandler);
            }
        }
    }
}
